package uni.j2ee.forum.validator;

import com.sun.faces.util.MessageFactory;
import java.util.Collection;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import uni.j2ee.forum.model.ForumData;
import uni.j2ee.forum.model.ForumPost;

public class DuplicatePostValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException {
        final String text = (String) value;
        if (alreadyExists(text)) {
            final FacesMessage message = MessageFactory.getMessage(context, "validator_duplicatePost", FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }

    private boolean alreadyExists(String text) {
        final Collection<ForumPost> posts = ForumData.getInstance().getPosts();
        for (ForumPost post : posts) {
            if (text.equalsIgnoreCase(post.getContent())) {
                return true;
            }
        }
        return false;
    }
}
